package com.hzw.saas.common.verify.service.impl;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.annotation.PostConstruct;

import com.hzw.saas.common.verify.config.TemplateConfig;
import com.hzw.saas.common.verify.service.ITemplateFileService;
import com.hzw.saas.common.verify.util.TemplateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.SimpleCache;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zzl
 * @since 09/02/2021
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TemplateFileServiceImpl implements ITemplateFileService {

    private static final String PATH_KEY_PREFIX = "path:";
    // 预加载模板列表，key=templateName, value=templateContent
    private final SimpleCache<String, String> templateCache = new SimpleCache<>(new HashMap<>());
    private final TemplateConfig config;

    @PostConstruct
    private void init() {
        this.loadTemplateCache();
    }

    @Override
    public String getTemplateByName(String name) {
        log.debug("尝试获取模板, name={}", name);
        String template = templateCache.get(name);
        Assert.notNull(template, "未找到模板缓存：{}", name);
        return template;
    }

    @Override
    public String getTemplateByPath(String path) {
        log.debug("尝试获取模板, path={}",path);
        if (Objects.isNull(path)) {
            return "";
        }
        String key = PATH_KEY_PREFIX.concat(path.trim());
        String template = templateCache.get(key);
        // 找到缓存
        if (Objects.nonNull(template)) {
            return template;
        }
        // 新建缓存
        File file = FileUtil.file(path);
        Assert.isTrue(FileUtil.isFile(file), "未找到模板文件：{}", path);
        template = FileUtil.readString(file, StandardCharsets.UTF_8);
        templateCache.put(key, template);
        return template;
    }

    @Override
    public String getContentByTemplate(String template, Map<String, String> params) {
        return TemplateUtil.getContentByTemplate(template, params);
    }

    @Override
    public String getContentByTemplateName(String name, Map<String, String> params) {
        String template = this.getTemplateByName(name);
        return this.getContentByTemplate(template, params);
    }

    @Override
    public String getContentByTemplatePath(String path, Map<String, String> params) {
        String template = this.getTemplateByPath(path);
        return this.getContentByTemplate(template, params);
    }

    // ================================================ private method ================================================ //

    private void loadTemplateCache() {
        log.debug("加载模板缓存...");
        if (StrUtil.isBlank(config.getDir())) {
            log.warn("无模板父目录配置，停止加载模板缓存");
            return;
        }
        File dir = FileUtil.file(config.getDir());
        if (!FileUtil.isDirectory(dir)) {
            log.warn("未找到模板父目录：{}", dir);
            return;
        }
        File[] files = dir.listFiles(File::isFile);
        if (ArrayUtil.isEmpty(files)) {
            return;
        }
        for (File file : files) {
            String key = file.getName();
            String value = FileUtil.readString(file, StandardCharsets.UTF_8);
            log.debug("加载模板缓存: {}", file);
            templateCache.put(key, value);
        }
    }
}
